Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/DbTerminal.jsm");
Components.utils.import("resource://gre/modules/k9mailDb.jsm");
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
/*设备信息对象数组初始化*/
var deviceInfo = [{status:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
/*全局设备信息*/
//var deviceName =null;
var offdeviceName=null;
var deviceSYS="Android";
var gDeviceWindowObj = null;
var liveoffStatus=null;
/*全局监控数组，当数组内增添新设备，或移除设备时触发*/
var addflag = null;
var rmflag = null;
var devlivenum=null;
var myObservableArray = ko.observableArray();
//var i=0;
myObservableArray.subscribe(function (newVal) {

    var dateval = Date.now();
    //flag = true;
    if (rmflag === "removeOk" && liveoffStatus==="liveon")
    {
        //alert('removeOK');
        //alert("removeOK");
        document.getElementById('offline').setAttribute('label', dateval);
        rmflag = null;
        liveoffStatus="liveoff";
        var accCP=window.frames["accountCentralPane"];
        var labelV=accCP.document.getElementById('AccountCentralTitle');
        labelV.setAttribute("value","DFuse Mail - Terminal Mail");
        var displayDesk = document.getElementById("displayDeck");
        displayDesk.setAttribute('selectedIndex','0');
        var coll=document.getElementById("messagepaneboxwrapper");
        coll.setAttribute('collapsed',true);
        var qfbbar=document.getElementById("qfb-show-filter-bar");
        var afbbox=document.getElementById("quick-filter-bar");
        afbbox.setAttribute('collapsed',true);
        qfbbar.setAttribute('checked',false);
        qfbbar.setAttribute('disabled',true);
    }
    if (addflag === "add")
    {
        //alert('add');
        //var newdevice=deviceName;
       // i++;
       // alert("push="+i+"次");
        document.getElementById('online').setAttribute('label', dateval);
        addflag = null;
    }
    //alert("全局数组长度="+newVal.length);

});
/*触发离线提醒*/
function getDeviceBey()
{
   
    var deviceLoser = offdeviceName + "设备离线";
    
    var alertsService = Components.classes["@mozilla.org/alerts-service;1"].
            getService(Components.interfaces.nsIAlertsService);
    try {
        var timestring = getAliveAndBeyTime();
        alertsService.showAlertNotification('', deviceLoser, timestring, false, '', null, '');
        deviceLoser=null;
    } catch (e)
    {
        debug("发生错误 => " + timestring + "\n");
    }

}
/*触发上线提醒*/
function getDeviceAlive()
{
    
    //myObservableArray()[devlivenum].name
    
    var devlist = gEN.getdevice();
    var uuid = Components.ID("{5aaf3bbd-993e-4402-a1ea-73a1a07a6e4b}");
    var device = devlist.queryElementAt(devlivenum, uuid);
    var ondevname=convertToUnicode(device.name);
    var messageString = ondevname + "设备已在线，      " + "该设备的操作系统类型为： " + deviceSYS + "，上线" + getAliveAndBeyTime() + "。";
    var box = document.getElementById("deviceOnLine");//msg-footer-notification-box
    box.setAttribute("statustext",device.uuid);
    
//    var notification = box.getNotificationWithValue(device.uuid);
//    if (notification) {
//    notification.label = messageString;
//    }   
    var buttons = [{
            label: '连接',
            accessKey: '连',
            popup: null,
            callback: function (aNotificationBar, aButton)
            {
                //alert(ondevname);
                 var flag;
                 var numberc;
                 var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dHandleStatus,count(dId) AS numbers FROM td_device where dUDN = :myVal");
                  statement.params.myVal = device.uuid;
                 try {
                 while (statement.executeStep()) {
                       flag = statement.row.dHandleStatus;
                       numberc= statement.row.numbers;
                      }
                   }
                 finally {
                  statement.reset();
                }
                if(numberc===0||flag)
                {
                     box.removeCurrentNotification();
                }
                else
                {
                    toShowlinkDevicePanel(device,dDeviceSqlite);
                }
                
            }
        }];

    var priority = box.PRIORITY_INFO_LOW;
    box.appendNotification(messageString, device.uuid, 'chrome://messenger/skin/icons/link.png', priority, buttons);
    var num =box.childNodes.length;
    box.setAttribute("ordinal",num);
   
    var notification = box.getNotificationWithValue(device.uuid);
    notification.setAttribute("ordinal",num);
    setTimeout(function(){notification.close();},60000);
}

/*触发同步提醒*/
function showSyncInfo()
{
    dDeviceSqlite.onLoad();
    var tempSync=gEN.sync;
//   var tempSync=1;
    if(tempSync!==null)
    {
        //alert(tempSync);
        var boxsync = document.getElementById("syncinfonotify");
        var allAccount = tempSync.split(":");
        for(var i = 0;i < allAccount.length - 1;i++)
        {
            var oneAccount = allAccount[i].split("_");
//            for(var j = 0; j < oneAccount.length;j++)
//            {
//                alert(oneAccount[j]);
//            }
            var accountXml = oneAccount[1] + ".sqlite";
            //alert(oneAccount[0]);
            var statement = dDeviceSqlite.dbConnection.createStatement("\
            SELECT dId FROM td_device WHERE dName = :myVal and dHandleStatus= :myVal1"); 
            statement.params.myVal =oneAccount[0];
            statement.params.myVal1 =1;
            var deviceId = null;
            try{
                    while(statement.executeStep()){
                    deviceId = statement.row.dId;
                    continue;
                }
            }
            finally{
                    statement.reset();
            }
//            if(deviceId)
//            {
//                alert("null");
//                return;
//            }
            //alert(deviceId);
            statement = dDeviceSqlite.dbConnection.createStatement("\
                     SELECT aId,aName,aXml FROM td_account WHERE dId = :myVal");
            statement.params.myVal =deviceId;
            var tempXml = null;
            var accoutName = null;
            try{
                    while(statement.executeStep())
                    {
                        tempXml = statement.row.aXml;
                        if(tempXml === accountXml)
                        {                       
                            accoutName = statement.row.aName;
                        }
                        continue;
                    }
            }
            finally{
                    statement.reset();
            }
            var recv = null;
            var send = null;
            var draft = null;
            if(oneAccount[2][0] === "1")
            {
                recv = "发件箱";
            }
            else
            {
                recv = null;
            }
            
            if(oneAccount[2][1] === "1")
            {
                send = "收件箱";
            }
            else
            {
                send = null;
            }
            if(oneAccount[2][2] === "1")
            {
                draft = "草稿箱";
            }
            else
            {
                draft = null;
            }
            if(send !== null || recv !==null || draft !==null)
            {
                var devname=convertToUnicode(oneAccount[0]);
                var message = devname + " 设备的 " + accoutName + " 账户的 ";
                if(send !== null)
                    message += send;
                if(recv !== null)
                    message += recv;
                if(draft !== null)
                    message += draft;
                message += "有同步请求";
                  //alert(message);
                //msg-footer-notification-box
                var notifyId= accoutName;
                var priority = boxsync.PRIORITY_INFO_LOW;
                //alert(accoutName);
                boxsync.appendNotification(message, notifyId, 'chrome://messenger/skin/icons/syncnotify.png', priority, "");
                //var num =boxsync.childNodes.length;
                //boxsync.setAttribute("ordinal",num);
   
                //var notifications = boxsync.getNotificationWithValue(accoutName);
                //notifications.setAttribute("ordinal",num);          
            }
           
        }
       gEN.sync=null; 
    }
    else
    {
    }
    
}
//setTimeout(getDeviceAliveOrBey,500);
//window.addEventListener("load",getDeviceAliveOrBey,false);
//window.setInterval(getDeviceAliveOrBey,60000);


/*获取上线及下线时间*/
function getAliveAndBeyTime()
{
    var date1 = new Date();
    var nowdateString = "时间：  " + date1.getHours().toString() + "时" + date1.getMinutes().toString() + "分" + date1.getSeconds().toString() + "秒";
    return nowdateString;
}

//window.addEventListener("load",testComponents,false);
/*启动TB时自动开启UPNP服务*/
window.addEventListener("load", function () {
    setTimeout(function () {
        upnpInit();
        dDeviceSqlite.onLoad();
    }, 0);
});
/*TB关闭时关闭UPNP服务*///compose-window-close beforeunload focus mousemove
window.addEventListener("close", closeUpnpService, false);

/*upnp服务初始化*/
var gEN = Components.classes["@nfs.hlj/upnpservice;1"].getService();//createInstance(Components.interfaces.nsIUpnpService);
gEN = gEN.QueryInterface(Components.interfaces.nsIUpnpService);

var lisenerDevlist=function () {
    setTimeout(function () {getDeviceArray();}, 0);};

var lisenerSyncInfo=function () {
    setTimeout(function () {showSyncInfo();}, 0);};

/*开启UPNP服务*/
function upnpInit()
{
    //alert("start");
    //deleteDeviceInfoInDB();
    
    gEN.upnpinit();
    //getDeviceArray();
    var dirService = Components.classes["@mozilla.org/file/directory_service;1"].
    getService(Components.interfaces.nsIProperties);
    var dir = dirService.get("ProfD", Components.interfaces.nsIFile);
    var pathS = dir.path;
    var lpath="../../../.."+pathS;
    //alert(lpath);
    gEN.path=lpath;
    //var a=gEN.path;
    //alert(a);
    window.addEventListener("focus",lisenerDevlist,false);
    window.addEventListener("mousemove",lisenerDevlist,false);
    
    window.addEventListener("focus",lisenerSyncInfo,false);
    window.addEventListener("mousemove",lisenerSyncInfo,false);
    
     var notifyBox = document.getElementById("mail-notification-box");
     try{
     if(notifyBox)
     {
         notifyBox.removeCurrentNotification();
     }}catch(e)
     {
       
     }
}
/*关闭UPNP服务*/
function closeUpnpService()
{
    
    //gEN.finishupnp();
    window.removeEventListener("focus",lisenerDevlist,false);
    window.removeEventListener("mousemove",lisenerDevlist,false);
    //alert(1);
    window.removeEventListener("focus",lisenerSyncInfo,false);
    window.removeEventListener("mousemove",lisenerSyncInfo,false);
   // alert(2);
    
    deleteDeviceInfoInDB();   //删除数据库中的设备表及账户表,信息头表，及通讯录表
    //alert(3);    
    //rmflag="removeOk";
    gEN.finishupnp();
    myObservableArray.removeAll();
    var panelTree = document.getElementById("folderPaneBox");
    var elem_child = panelTree.childNodes; 
     //alert(menuItem.getAttribute("checked"));
     if(panelTree){
         for(var i=0;i<elem_child.length;i++){
            if("showDevicesPanelTree"=== elem_child[i].id){
                  elem_child[i].parentNode.removeChild(elem_child[i]);         
            }
         }
     }
   var  treeSpr = document.getElementById("hadTreeOrNewTree");
    if(treeSpr){
        treeSpr.parentNode.removeChild(treeSpr);
     }
}


/*测试发送指定的动作*/
function sentActionTest()
{
    var locationStr;
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dLocation FROM td_device where dHandleStatus = :myVal");
                  statement.params.myVal = 1;
                 
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    alert(serviceSubStr);
    gEN.SendAction(serviceSubStr,"PowerOn","deviceInfo.xml"); 
    alert("动作完成");
}
/*字符转码UTF-8,主要用于读文件*/
//function convertToUnicode(aStr) {  
// }  
///*字符转码，主要用于写文件*/
//function convertFromUnicode(aStr) {  
// }  
/*比较当前入网设备数组与全局监控数组
 * 
 * 判断入网设备数组内元素变化，新增设备调用函数addDev()
 * 移除设备调用函数 removeDev()
 * */
function getDeviceArray()
{
    //alert(1111111111);
    //gEN.checkstateflag="";
    var devlist = gEN.getdevice();
    var uuid = Components.ID("{5aaf3bbd-993e-4402-a1ea-73a1a07a6e4b}");
    //alert(gEN.checkstateflag);
    if(devlist.length!==0)//&&gEN.checkstateflag!=="none"
    {    
      //alert("devlist.length="+devlist.length); 
       if(addDev(devlist,uuid))
       {   
         removeDev(devlist,uuid);
       }   
     }
     /*唯一在线设备的离线与beybey退出*/
 if(devlist.length===0 && myObservableArray().length===1)//
 {
         //gEN.checkstateflag="";  
        //alert("进入我"+gEN.checkstateflag)
        
        //gEN.checkstateflag="abcd";
        var lastdevice=myObservableArray()[0];
        offdeviceName=convertToUnicode(lastdevice.name);
        deleteOffDevDBInfo(lastdevice.uuid);
        //alert("删除唯一在线设备=");
        rmflag = "removeOk";
        myObservableArray.remove(lastdevice);
        //myObservableArray.removeAll();
 }
   /*    
   else if(gEN.getdevice().length===0&&gEN.checkstateflag==="have")
       {
        alert("删除唯一在线设备="+gEN.checkstateflag);
        gEN.checkstateflag="abcd";
        var lastdevice=myObservableArray()[0];
        offdeviceName=convertToUnicode(lastdevice.name);
        deleteOffDevDBInfo(lastdevice.uuid);
        rmflag = "removeOk";
        myObservableArray.remove(lastdevice);
       } */ 
        //removeDev(devlist,uuid);    
    
}
//var complexListModel = function(items) {
//            var self = this;
//            self.items = [];
//            ko.utils.arrayForEach(items, function (item) {
//                var i = {
//                    num:ko.observable(item.num),
//                    addr:ko.observable(item.addr),
//                    name:ko.observable(item.name),
//                    prob:ko.observable(item.prob)
//                };
//                self.items.push(i);
//            });
//            self.items = ko.observableArray(self.items);
//        };
/*设备上线,添加设备到列表
 * 
 * 传入新上线的设备，更新全局数组
 *
 * */
function addDev(devlist,uuid)
{
   //alert(devlist.length);
     for (var i = 0; i < devlist.length; i++)
      {
        //alert(i);
        var device = devlist.queryElementAt(i, uuid);
        //alert("device"+i+"的名字="+device.name);
        var easitflag;
                
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT count(dId) AS numbers FROM td_device where dUDN = :myVal");
                  statement.params.myVal = device.uuid;
                 
        try {
                 while (statement.executeStep()) {
                       easitflag = statement.row.numbers;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
                //myObservableArray.indexOf(device) === -1
                //alert("easitflag="+easitflag);
        if (easitflag===0)
        {
            //alert(easitflag+"addflag");
            //alert("11111111");
            addflag = "add";
            //alert("addev->gEN.checkstateflag="+gEN.checkstateflag);
            var deviceName=convertToUnicode(device.name);
            //var deviceInfo = [{status:0, name:"设备名", UDN:"设备描述码", listID:"dev_0"}];
            addOneDeviceInfo(deviceInfo, 0, device.location,deviceName, device.uuid);
            getOneDeviceInfos(deviceInfo);
            deviceInfo.length = 0;//ary.length = 0;
            devlivenum=i;
            //alert("device"+i+"的名字="+deviceName); 
            myObservableArray.push(device);
        }

      }
      return 1;
}

/*设备下线，移除设备到列表
 * 
 *传入移除的设备，更新全局列表
 *更新数据库内信息
 * 
 * */
function removeDev(devlist,uuid)
{
    
    //var revOprFlag=true;
    var getlistid;
    var deletedevid;
    var deviceL=devlist.length;
    //alert("devlist.length的长度为："+devlist.length);
     for (var j = 0; j < myObservableArray().length; j++)
    {
        //alert("deviceL="+deviceL);
        for (var i = 0; i < deviceL; i++)    
      {
        var device = devlist.queryElementAt(i, uuid);  
        if (myObservableArray()[j].uuid!==device.uuid)
        {
       
            //alert("第一步-》"+"saveFlagState[i]值为："+saveFlagState[i]);
            getlistid = i+1;
            deletedevid=j;
            //alert("deletedevid="+deletedevid);
            //alert("getlistid="+getlistid);
            continue;  
        }else{
            //alert("jump");
            break;
        
            }
          
            
      }
      if(getlistid===deviceL)  
      {
            rmflag = "removeOk";
            deleteOffDevDBInfo(myObservableArray()[deletedevid].uuid);  
            offdeviceName=convertToUnicode(myObservableArray()[deletedevid].name);  
            myObservableArray.remove(myObservableArray()[deletedevid]);
                   
      }    

 }
}
/*删除下线设备已存储的信息*/

function deleteOffDevDBInfo(id)
{
    
    var offdeviceid;
    var emailAccount=[];
    var deviceNS;
    var offdevicestatus;
    var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT dId,dStatus  FROM td_device where dUDN = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                        offdeviceid= statement.row.dId;
                        offdevicestatus= statement.row.dStatus;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
      if(offdevicestatus==0)
      {   
          liveoffStatus="liveoff";
      }else{
          liveoffStatus="liveon";
      }
            //alert(offdeviceid);
      var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT aXml  FROM td_account where dId = :myVal");
                  statement.params.myVal = offdeviceid;
                 
        try {
                 while (statement.executeStep()) {
                        emailAccount.push(statement.row.aXml);
                      }
                   }
                 
        finally {
                  statement.reset();
                }  
         /*删除离线设备内账户数据信息*/
          Components.utils.import("resource://gre/modules/FileUtils.jsm");
          for(var i=0;i<emailAccount.length;i++)
          { 
            var dbname=emailAccount[i];  
            var dbFile = FileUtils.getFile("ProfD", [dbname]);
            if(dbFile.exists())
            {
              dbFile.remove(true);
            }else{
                continue;
            }
          }   
//             var statement = dDeviceSqlite.dbConnection.createStatement("\
//                  DELETE FROM td_email WHERE dId =:myVal");
//                  statement.params.myVal = offdeviceid;
//            try{
//               statement.executeStep();
//            }
//            finally{
//                statement.reset();
//            }      
         //alert(2);
     /*更新离线设备的通讯录状态信息*/
      var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT dName FROM td_device where dId = :myVal");
                  statement.params.myVal = offdeviceid;
                 
        try {
                 while (statement.executeStep()) {
                       deviceNS=statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }  
      //alert(3); 
      //alert(deviceNS);
     try{
         var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT cDeviceName FROM td_contact where cDeviceName = :myVal");
        statement.params.myVal = deviceNS;
        while(statement.executeStep()){
            var easitFlag= statement.row.cDeviceName;
           }
        }
    finally{
        statement.reset();
     }
     //alert(easitFlag);
     if(easitFlag===deviceNS)
     {    
      var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_contact \
                           SET cStatus = :myVal1  where cDeviceName = :myVal");
      statement.params.myVal = deviceNS;
       statement.params.myVal1 = 3;
      try {
        while (statement.executeStep()) {
            continue;
        }
      }
    finally {
        statement.reset();
    }
     }
    //alert(4);
    /*更新远程邮件目录树，删除离线设备*/            
    breakoffliveoffDevice(offdeviceid);             
    //alert(5); 
        /*删除数据库中存储的设备信息*/
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_device WHERE dUDN = :myVal");
            statement.params.myVal = id;
            try{
                 statement.executeStep();
            }
            finally{
                statement.reset();
            }
            
  
}

function toShowlinkDevicePanel(dev,dbdev)
{
    //var folderPane =  document.getElementById('folderPaneBox');
    //var selectMenuItem = document.getElementById("connectManagerPanel");
    //alert(newdevice);
     //gEN.deviceid = dev.uuid;
     //alert(gEN.deviceid);
    var locationStr=dev.location;
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/event/tvcontrol1";
    //alert(serviceSubStr);
    gEN.connectDevice(serviceSubStr); 
   // alert("xx");
    if(gDeviceWindowObj === null || gDeviceWindowObj.closed){  
        gDeviceWindowObj = window.openDialog(
                "chrome://messenger/content/onedeviceWindow.xul", 
                "deviceWindowName",
                "chrome, dialog, centerscreen",dev,dbdev);
    }else{
        gDeviceWindowObj.close();
    }
}
/*断开服务时删除数据库中的设备信息表*/
function deleteDeviceInfoInDB()
{
    /*删除原设备表并建立新设备表*/
   dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_device");
   dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_device (\
                dId INTEGER PRIMARY KEY AUTOINCREMENT, dName CHAR(50) NOT NULL,  dLocation TEXT NOT NULL, dUDN TEXT NOT NULL,\
                dStatus INTEGER DEFAULT 0, dHandleStatus INTEGER DEFAULT 0, dListId INTEGER)");
   
  /*删除所有终端邮件账户的数据库文件*/
         var emailAccount=[];
         var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT aXml FROM td_account");        
         try {
                 while (statement.executeStep()) {
                        emailAccount.push(statement.row.aXml);
                      }
                   }
                 
        finally {
                  statement.reset();
                }  

          Components.utils.import("resource://gre/modules/FileUtils.jsm");
          for(var i=0;i<emailAccount.length;i++)
          { 
            var dbname=emailAccount[i];  
            var dbFile = FileUtils.getFile("ProfD", [dbname]);
            if(dbFile.exists())
            {
              dbFile.remove(true);
            }else{
                continue;
            }
          }  
    /*删除原账户信息表并建立新账户信息表*/
    dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_account");
    dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_account (\
                                                aId INTEGER PRIMARY KEY AUTOINCREMENT,\
                                                aName CHAR(50) NOT NULL,aPwd CHAR(50) \
                                                NOT NULL,aXml TEXT NOT NULL,aServiceType\
                                                INTEGER,dId INTEGER NOT NULL,aLastStatus \
                                                INTEGER DEFAULT 0,aLocalStatus INTEGER DEFAULT 0,\
                                             aRemoteStatus INTEGER DEFAULT 0,aControlType INTEGER DEFAULT 0)");
 
  /*删除原邮件头信息表并建立新邮件头信息表*/
//   dDeviceSqlite.dbConnection.executeSimpleSQL("DROP TABLE td_contact");   
//   dDeviceSqlite.dbConnection.executeSimpleSQL("CREATE TABLE IF NOT EXISTS td_email (\
//                                             cId           INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
//                                             cDeviceName        VARCHAR NOT NULL,\
//                                             cContactName         VARCHAR NOT NULL,\
//                                             cEmailAddress      VARCHAR NOT NULL,\
//                                             cAccount               VARCHAR NOT NULL,\
//                                             cUri                       VARCHAR,\
//                                             cStatus                  INTEGER DEFAULT 1)"; 
   //alert(5);
   var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_contact \
                           SET cStatus =:myVal");
      statement.params.myVal =3;
      try {
        while (statement.executeStep()) {
            continue;
        }
      }
    finally {
        statement.reset();
    }
   dDeviceSqlite.onClose();
   //alert(6);
}

/*控制UPNP服务*/
function controlUpnpService()
{
    
    var selectMenuItem = document.getElementById("swithUpnpServ");
    if(selectMenuItem.getAttribute("checked"))
    {
        upnpInit();
        //alert(1);        
    }else{
        //alert(2);
        closeUpnpService();
    }
}

function testReadDb()
{
    var dirService = Components.classes["@mozilla.org/file/directory_service;1"].
          getService(Components.interfaces.nsIProperties);
    var dir = dirService.get("ProfD", Components.interfaces.nsIFile);//TmpD
    alert(dir.path);
    if(dk9Sqlite.onLoad("73bc68c4-6616-495d-8b0e-33af0b430583.sqlite"))
    {
      var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT subject FROM  messages WHERE id = :myVal");
      statement.params.myVal =1;
      try{
         while(statement.executeStep())
         {
            alert(statement.row.subject);  
         }
    }
    finally
    {
        statement.reset();
    }
     alert(3);
    } 
}
